package com.data.modules.log.service.impl;



import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data.common.exception.BootException;
import com.data.common.system.vo.DictModel;
import com.data.common.util.AliyunUtil;
import com.data.common.constant.enums.ApiEnum;
import com.data.config.AliyunConfig;
import com.data.modules.system.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import com.data.modules.log.entity.ApiLog;
import com.data.modules.log.mapper.ApiLogMapper;
import com.data.modules.log.service.IApiLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 请求三方api日志
 * @Author: data-boot
 * @Date:   2022-01-06
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApiLogServiceImpl extends ServiceImpl<ApiLogMapper, ApiLog> implements IApiLogService {

    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private ApiLogMapper apiLogMapper;
    @Autowired
    private ISysDictService iSysDictService;

    @Override
    public List<ApiLog> apiCheck(Integer types,String requestParams) {
        List<ApiLog> apiLogs = new LinkedList<>();
        log.debug("=======验证类型==>{},=====请求参数==={}",types,requestParams);

        if(ObjectUtil.isEmpty(requestParams)){
            throw new BootException("请求参数不能为空!");
        }
        if(ObjectUtil.isEmpty(types)){
            throw new BootException("请输入要验证的类型!");
        }
        switch (Objects.requireNonNull(ApiEnum.getInstanceByCode(types))){
            //企业查询
            case  COMPANY_TYPE_100:{
                 checkCompany(apiLogs,JSONObject.parseObject(requestParams));
                break;
            }
            //todo 其他api查询
            default: {
                throw new BootException("请输入正确的查询类型");
            }
        }
        return apiLogs;
    }

    @Override
    public List<ApiLog> checkCompanyByCode(String socCode, String company) {
        //基本参数校验
        if(ObjectUtil.isEmpty(socCode) || ObjectUtil.isEmpty(company)){
            throw new BootException("请输入企业信息");
        }

        //调用api查询公司信用代码（注：通过信用代码去查询）
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("company",socCode);
        List<ApiLog> apiLogs = new LinkedList<>();
        //调用api查询结果
        List<ApiLog> logs = checkCompany(apiLogs, jsonObject);
        //①未查到 说明填写有误
        if(logs.size() == 0){
            throw new BootException("企业名称与统一信用代码不正确，请校验后再次提交");
        }
        //②查到了 判断输入的公司名和查到返回的公司名进行比对
        //对传过来的公司名称中带括号的进行统一处理，英文括号处理为中文
        String rc = company.replaceAll("\\(", "（");
        String s = rc.replaceAll("\\)", "）");
        //未查到 数据库该字段为空 信用代码不正确
        if(ObjectUtil.isEmpty(logs.get(0).getKeyExt1())){
            throw new BootException("企业名称与统一信用代码不正确，请校验后再次提交");
        }
        //查出来的企业名称也对带括号的统一处理
        String apiCompany = logs.get(0).getKeyExt1().replaceAll("\\(", "（");
        String apiRepalce = apiCompany.replaceAll("\\)", "）");

        //添加开关控制
        DictModel switchModel = iSysDictService.querySysDictInfoByCode("company_validate_switch");

        if(ObjectUtil.isNotEmpty(switchModel) && ObjectUtil.equal("Y",switchModel.getValue())){
            //将传过来的企业名称 和 api查询到的企业名称均替换为中文括号
            if(ObjectUtil.notEqual(s,apiRepalce)){
                throw new BootException("企业名称与统一信用代码不正确，请校验后再次提交");
            }
        }

        return logs;
    }

    @Override
    public List<ApiLog> queryAll() {
        List<ApiLog> apiLogs = this.lambdaQuery()
                .eq(ApiLog::getBizCode,1)
                .select(ApiLog::getKeyExt1,ApiLog::getKeyExt2,ApiLog::getKeyExt4)
                .list();
        return apiLogs;
    }

    /**
     * 调用api查询企业信息
     * @param apiLogs 对象结果集封装数据
     * @param requestParams 请求参数
     * @auth xiayuanpeng
     */
    private List<ApiLog> checkCompany(List<ApiLog> apiLogs,JSONObject requestParams) {
        //查询最后返回的结果集
        String company = requestParams.getString("company");
        //将英文括号 全部替换为 中文括号
        String rc = company.replaceAll("\\(", "（");
        String s = rc.replaceAll("\\)", "）");
        //按逗号分隔后循环查阿里查询企业api
        String[] companys = s.split(",");
        for (String p : companys) {
            String responseBody = null;

            //添加开关控制
            DictModel switchModel = iSysDictService.querySysDictInfoByCode("company_validate_switch");

            if(ObjectUtil.isNotEmpty(switchModel) && ObjectUtil.equal("Y",switchModel.getValue())){
                try {
                    responseBody = AliyunUtil.alyCompanyCheck(aliyunConfig, p);
                } catch (Exception e) {
                    log.error("=====企业工商信息查询错误信息====>{}",e.getMessage());
                }
            }

            log.debug("企业工商信息查询返回======>{}",responseBody);
            //封装
            ApiLog aLog = new ApiLog();
            aLog.setCreateTime(new Date());
            aLog.setUpdateTime(new Date());
            aLog.setTypes(ApiEnum.COMPANY_TYPE_100.getTypes());
            aLog.setRequestParams(p);
            aLog.setBizCode(0);
            if(ObjectUtil.isNotEmpty(responseBody)){
                /** 记录查询日志 */
                JSONObject jsonObject = JSONObject.parseObject(responseBody);

                aLog.setResponseMsg(responseBody);
                //企业名称
                aLog.setKeyExt1(jsonObject.getJSONObject("result").getString("companyName"));
                //法人名称
                aLog.setKeyExt2(jsonObject.getJSONObject("result").getString("faRen"));
                //信用代码
                aLog.setKeyExt3(jsonObject.getJSONObject("result").getString("creditCode"));
                //注册地址
                aLog.setKeyExt4(jsonObject.getJSONObject("result").getString("address"));
                //error_code 为0 查询成功，50002查询失败
                aLog.setBizCode(0 == jsonObject.getInteger("error_code") ? 1 : 0);
                aLog.setBizMsg(jsonObject.getString("reason"));
            }else{

                //企业名称
                aLog.setKeyExt1("测试");
                //法人名称
                aLog.setKeyExt2("测试");
                //信用代码
                aLog.setKeyExt3(IdUtil.simpleUUID());
                //注册地址
                aLog.setKeyExt4(IdUtil.simpleUUID());
                //error_code 为0 查询成功，50002查询失败
                aLog.setBizCode(0);
            }
            this.save(aLog);
            apiLogs.add(aLog);
        }
        return apiLogs;
    }

}
